package com.project.srtp.secure.exception;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import java.util.Map;

/**
 * @author 曹行阳
 * @version 0.1
 * @date 2025/6/11 11:19
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(ComplianceViolationException.class)
    public ResponseEntity<Map<String, String>> handleComplianceViolation(ComplianceViolationException ex) {
        System.err.println("COMPLIANCE VIOLATION: " + ex.getMessage() + ". Initiating disposal mechanism.");

        Map<String, String> response = Map.of(
                "error", "Forbidden",
                "message", ex.getMessage(),
                "status", "403"
        );
        return new ResponseEntity<>(response, HttpStatus.FORBIDDEN);
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<?> handleValidationException(MethodArgumentNotValidException ex) {
        return ResponseEntity.badRequest().body("参数绑定异常: " + ex.getMessage());
    }

    @ExceptionHandler(HttpMessageNotReadableException.class)
    public ResponseEntity<?> handleJsonParseException(HttpMessageNotReadableException ex) {
        return ResponseEntity.badRequest().body("JSON 解析失败: " + ex.getMessage());
    }

    @ExceptionHandler(Exception.class)
    public ResponseEntity<?> handleOtherException(Exception ex) {
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("服务器异常: " + ex.getMessage());
    }
}
